package aes.client;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;

import common.*;

public class QuestionEditorUI extends JPanel implements ActionListener, Observer{

	private static final long serialVersionUID = 7942127226844931169L;

	private ClientUI ui;
	private Client c;
	private JButton btnCancel;
	private JButton btnSave;
	private JTextField txtQuestionNum;
	private JTextField txtQuetion;
	private JTextField txtAnswer1;
	private JTextField txtAnswer2;
	private JTextField txtAnswer3;
	private JTextField txtAnswer4;
	private JTextField txtNotes;
	private JComboBox cmbSubjectNum;
	private JComboBox cmbCorrectAnswer;
	private int qID=0;

	/**
	 * Constructor
	 * @param c Client object
	 * @param ui ClientUI object
	 */
	public QuestionEditorUI(Client c,ClientUI ui) {
		super();
		this.ui = ui;
		this.c = c;
		c.addObserver(this);
		setLayout(new GridBagLayout());
		
		JFrame frame = new JFrame();
		frame.setSize(640, 480);
		frame.add(this);
		
		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
		panel.setPreferredSize(new Dimension(600,400));

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(5, 0, 5, 0);
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel,gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0};
		panel.setLayout(gbl_panel);

		JLabel lblAesTitle = new JLabel("Questions Editor");
		lblAesTitle.setVerticalAlignment(SwingConstants.TOP);
		lblAesTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblAesTitle.setBounds(7, 10, 70, 17);
		lblAesTitle.setFont(new Font("Tahoma", Font.BOLD, 14));

		GridBagConstraints gbc_lblAesTitle = new GridBagConstraints();
		gbc_lblAesTitle.anchor = GridBagConstraints.NORTH;
		gbc_lblAesTitle.gridwidth = 2;
		gbc_lblAesTitle.fill = GridBagConstraints.BOTH;
		gbc_lblAesTitle.insets = new Insets(5, 0, 5, 0);
		gbc_lblAesTitle.gridx = 0;
		gbc_lblAesTitle.gridy = 0;
		panel.add(lblAesTitle, gbc_lblAesTitle);

		JLabel lblNewLabel = new JLabel("Subject #:");
		lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
		gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel.gridx = 0;
		gbc_lblNewLabel.gridy = 1;
		panel.add(lblNewLabel, gbc_lblNewLabel);

		cmbSubjectNum = new JComboBox();
		GridBagConstraints gbc_cmbSubjectNum = new GridBagConstraints();
		gbc_cmbSubjectNum.insets = new Insets(0, 0, 5, 10);
		gbc_cmbSubjectNum.fill = GridBagConstraints.HORIZONTAL;
		gbc_cmbSubjectNum.gridx = 1;
		gbc_cmbSubjectNum.gridy = 1;
		panel.add(cmbSubjectNum, gbc_cmbSubjectNum);

		JLabel lblQuestion = new JLabel(" Question #:");
		lblQuestion.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblQuestion = new GridBagConstraints();
		gbc_lblQuestion.anchor = GridBagConstraints.EAST;
		gbc_lblQuestion.insets = new Insets(0, 0, 5, 5);
		gbc_lblQuestion.gridx = 0;
		gbc_lblQuestion.gridy = 2;
		panel.add(lblQuestion, gbc_lblQuestion);

		txtQuestionNum = new JTextField();
		GridBagConstraints gbc_txtQuestionNum = new GridBagConstraints();
		gbc_txtQuestionNum.insets = new Insets(0, 0, 5, 10);
		gbc_txtQuestionNum.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtQuestionNum.gridx = 1;
		gbc_txtQuestionNum.gridy = 2;
		panel.add(txtQuestionNum, gbc_txtQuestionNum);
		txtQuestionNum.setColumns(10);

		JLabel lblQuestion_1 = new JLabel("Question:");
		lblQuestion_1.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblQuestion_1 = new GridBagConstraints();
		gbc_lblQuestion_1.anchor = GridBagConstraints.EAST;
		gbc_lblQuestion_1.insets = new Insets(0, 0, 5, 5);
		gbc_lblQuestion_1.gridx = 0;
		gbc_lblQuestion_1.gridy = 3;
		panel.add(lblQuestion_1, gbc_lblQuestion_1);

		txtQuetion = new JTextField();
		txtQuetion.setText("");
		GridBagConstraints gbc_txtQuetion = new GridBagConstraints();
		gbc_txtQuetion.insets = new Insets(0, 0, 5, 10);
		gbc_txtQuetion.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtQuetion.gridx = 1;
		gbc_txtQuetion.gridy = 3;
		panel.add(txtQuetion, gbc_txtQuetion);
		txtQuetion.setColumns(10);

		JLabel lblanswer1 = new JLabel("Answer 1:");
		lblanswer1.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblanswer1 = new GridBagConstraints();
		gbc_lblanswer1.anchor = GridBagConstraints.EAST;
		gbc_lblanswer1.insets = new Insets(0, 0, 5, 5);
		gbc_lblanswer1.gridx = 0;
		gbc_lblanswer1.gridy = 4;
		panel.add(lblanswer1, gbc_lblanswer1);

		txtAnswer1 = new JTextField();
		GridBagConstraints gbc_txtAnswer1 = new GridBagConstraints();
		gbc_txtAnswer1.insets = new Insets(0, 0, 5, 10);
		gbc_txtAnswer1.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtAnswer1.gridx = 1;
		gbc_txtAnswer1.gridy = 4;
		panel.add(txtAnswer1, gbc_txtAnswer1);
		txtAnswer1.setColumns(10);

		JLabel lblanswer2 = new JLabel("Answer 2:");
		lblanswer2.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblanswer2 = new GridBagConstraints();
		gbc_lblanswer2.anchor = GridBagConstraints.EAST;
		gbc_lblanswer2.insets = new Insets(0, 0, 5, 5);
		gbc_lblanswer2.gridx = 0;
		gbc_lblanswer2.gridy = 5;
		panel.add(lblanswer2, gbc_lblanswer2);

		txtAnswer2 = new JTextField();
		txtAnswer2.setText("");
		GridBagConstraints gbc_txtAnswer2 = new GridBagConstraints();
		gbc_txtAnswer2.insets = new Insets(0, 0, 5, 10);
		gbc_txtAnswer2.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtAnswer2.gridx = 1;
		gbc_txtAnswer2.gridy = 5;
		panel.add(txtAnswer2, gbc_txtAnswer2);
		txtAnswer2.setColumns(10);

		JLabel lblanswer3 = new JLabel("Answer 3:");
		lblanswer3.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblanswer3 = new GridBagConstraints();
		gbc_lblanswer3.anchor = GridBagConstraints.EAST;
		gbc_lblanswer3.insets = new Insets(0, 0, 5, 5);
		gbc_lblanswer3.gridx = 0;
		gbc_lblanswer3.gridy = 6;
		panel.add(lblanswer3, gbc_lblanswer3);

		txtAnswer3 = new JTextField();
		txtAnswer3.setText("");
		GridBagConstraints gbc_txtAnswer3 = new GridBagConstraints();
		gbc_txtAnswer3.insets = new Insets(0, 0, 5, 10);
		gbc_txtAnswer3.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtAnswer3.gridx = 1;
		gbc_txtAnswer3.gridy = 6;
		panel.add(txtAnswer3, gbc_txtAnswer3);
		txtAnswer3.setColumns(10);


		JLabel lblanswer4 = new JLabel("Answer 4:");
		lblanswer4.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblanswer4 = new GridBagConstraints();
		gbc_lblanswer4.anchor = GridBagConstraints.EAST;
		gbc_lblanswer4.insets = new Insets(0, 0, 5, 5);
		gbc_lblanswer4.gridx = 0;
		gbc_lblanswer4.gridy = 7;
		panel.add(lblanswer4, gbc_lblanswer4);

		txtAnswer4 = new JTextField();
		GridBagConstraints gbc_txtAnswer4 = new GridBagConstraints();
		gbc_txtAnswer4.insets = new Insets(0, 0, 5, 10);
		gbc_txtAnswer4.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtAnswer4.gridx = 1;
		gbc_txtAnswer4.gridy = 7;
		panel.add(txtAnswer4, gbc_txtAnswer4);
		txtAnswer4.setColumns(10);

		String[] a= new String[]{"1","2","3","4"};

		cmbCorrectAnswer = new JComboBox(a);
		GridBagConstraints gbc_cmbCorrectAnswer = new GridBagConstraints();
		gbc_cmbCorrectAnswer.insets = new Insets(0, 0, 5, 10);
		gbc_cmbCorrectAnswer.fill = GridBagConstraints.HORIZONTAL;
		gbc_cmbCorrectAnswer.gridx = 1;
		gbc_cmbCorrectAnswer.gridy = 8;

		panel.add(cmbCorrectAnswer, gbc_cmbCorrectAnswer);

		JLabel lblcorrect = new JLabel("Correct Answer:");
		lblcorrect.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblcorrect = new GridBagConstraints();
		gbc_lblcorrect.anchor = GridBagConstraints.EAST;
		gbc_lblcorrect.insets = new Insets(0, 0, 5, 5);
		gbc_lblcorrect.gridx = 0;
		gbc_lblcorrect.gridy = 8;
		panel.add(lblcorrect, gbc_lblcorrect);

		JLabel lblnotes = new JLabel("Notes:");
		lblnotes.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblnotes = new GridBagConstraints();
		gbc_lblnotes.anchor = GridBagConstraints.EAST;
		gbc_lblnotes.insets = new Insets(0, 0, 5, 5);
		gbc_lblnotes.gridx = 0;
		gbc_lblnotes.gridy = 9;
		panel.add(lblnotes, gbc_lblnotes);

		txtNotes = new JTextField();
		GridBagConstraints gbc_txtNotes = new GridBagConstraints();
		gbc_txtNotes.anchor = GridBagConstraints.NORTH;
		gbc_txtNotes.insets = new Insets(0, 0, 5, 10);
		gbc_txtNotes.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtNotes.gridx = 1;
		gbc_txtNotes.gridy = 9;
		panel.add(txtNotes, gbc_txtNotes);
		txtNotes.setColumns(10);

		btnCancel = new JButton("Cancel", new ImageIcon(QuestionEditorUI.class.getResource("/aes/client/images/Cancel.png")));
		btnCancel.setHorizontalAlignment(SwingConstants.LEFT);
		btnCancel.addActionListener(this); 

		GridBagConstraints gbc_btnCancel = new GridBagConstraints();
		gbc_btnCancel.anchor = GridBagConstraints.WEST;
		gbc_btnCancel.insets = new Insets(5, (ui.getUser() instanceof Principal)? 10 : 0, 0, 0);
		gbc_btnCancel.gridx = (ui.getUser() instanceof Principal)? 0 : 1;
		gbc_btnCancel.gridy = 10;
		panel.add(btnCancel, gbc_btnCancel);
		btnCancel.setBounds(353, 7, 57, 23);

		btnSave = new JButton("Save", new ImageIcon(QuestionEditorUI.class.getResource("/aes/client/images/Save.png")));
		btnSave.addActionListener(this); 
		GridBagConstraints gbc_btnSave = new GridBagConstraints();
		gbc_btnSave.insets = new Insets(5, 5, 0, 5);
		gbc_btnSave.gridx = 0;
		gbc_btnSave.gridy = 10;
		panel.add(btnSave, gbc_btnSave);
		btnSave.setBounds(353, 7, 57, 23);

		this.initialize();

		if (ui.getUser() instanceof Principal) {
			btnSave.setVisible(false);
			btnCancel.setIcon(new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/back.png")));
			btnCancel.setText("Back");
			
			txtQuetion.setEditable(false);
			txtAnswer1.setEditable(false);
			txtAnswer2.setEditable(false);
			txtAnswer3.setEditable(false);
			txtAnswer4.setEditable(false);
			cmbCorrectAnswer.setEnabled(false);
			txtNotes.setEditable(false);
		}
	}

	/**
	 * Buttons click event handler
	 */
	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(btnCancel)) {
			// Back.
			ui.SetContent(ui.QUESTIONS_MANAGER_SCREEN);
		}
		else if (e.getSource().equals(btnSave)) {
			// Save
			if (!checkValues())
				return;
			Question q= new Question();
			int id=((Subject)cmbSubjectNum.getSelectedItem()).getId()*1000+Integer.parseInt(txtQuestionNum.getText());
			q.setId(id);
			q.setQuestion(txtQuetion.getText());
			q.setAnswers(new String[]{txtAnswer1.getText(),txtAnswer2.getText(),txtAnswer3.getText(),txtAnswer4.getText()});
			q.setCorrectAnswer(Integer.parseInt(cmbCorrectAnswer.getSelectedItem().toString()));
			q.setNotes(txtNotes.getText());
			q.setTeacherId(ui.getUser().getId());
			CommandMessage ms;
			if(this.qID==0){
				ms=new CommandMessage(CommandMessage.ADD_QUESTION,new Object[]{q});
			}
			else{
				ms=new CommandMessage(CommandMessage.EDIT_QUESTION,new Object[]{q});
			}
			try {
				c.sendToServer(ms);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * Initializes form
	 */
	private void initialize(){
		CommandMessage cm = new CommandMessage(CommandMessage.GET_SUBJECTS,null);
		try {
			c.sendToServer(cm);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Message received event handler
	 */
	@SuppressWarnings("static-access")
	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_SUBJECTS)) {
				Subject[] subjects = (Subject[]) ms.getParams()[1];

				if(subjects!=null){
					for (Subject c:subjects) 
						cmbSubjectNum.addItem(c);
				}
			}	
			else if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.ADD_QUESTION)) 
			{
				if(!Boolean.parseBoolean(ms.getParams()[2].toString()))
				{
					ui.ShowMessageBox("ERROR", "Can't add question", JOptionPane.ERROR_MESSAGE);
					return;
				}
				else 
					ui.SetContent(ui.QUESTIONS_MANAGER_SCREEN);
			}
			else if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.EDIT_QUESTION)) 
			{
				if(!Boolean.parseBoolean(ms.getParams()[2].toString()))
				{
					ui.ShowMessageBox("ERROR", "Can't update question", JOptionPane.ERROR_MESSAGE);
					return;
				}
				else 
					ui.SetContent(ui.QUESTIONS_MANAGER_SCREEN);
			}
			else if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_QUESTION)) 
			{
				Question q=(Question)ms.getParams()[1];
				if(q==null)
				{
					ui.ShowMessageBox("ERROR", "Can't find question", JOptionPane.ERROR_MESSAGE);
					ui.SetContent(ui.QUESTIONS_MANAGER_SCREEN);
				}
				else {
					txtQuestionNum.setText(Integer.toString(q.getQuestionID()));
					txtQuetion.setText(q.getQuestion());
					txtAnswer1.setText(q.getAnswers()[0]);
					txtAnswer2.setText(q.getAnswers()[1]);
					txtAnswer3.setText(q.getAnswers()[2]);
					txtAnswer4.setText(q.getAnswers()[3]);
					txtNotes.setText(q.getNotes());
					for(int i=0;i<cmbSubjectNum.getItemCount();i++){
						if(((Subject)cmbSubjectNum.getItemAt(i)).getId()==q.getSubject()){
							cmbSubjectNum.setSelectedIndex(i);
							break;
						}
					}
					for(int i=0;i<cmbCorrectAnswer.getItemCount();i++){
						if(cmbCorrectAnswer.getItemAt(i).toString().equals(Integer.toString(q.getCorrectAnswer()))){
							cmbCorrectAnswer.setSelectedIndex(i);
							break;
						}
					}
				}
			}
		}
	}	

	/**
	 * Validates input fields
	 * @return Validation result
	 */
	@SuppressWarnings("static-access")
	private boolean checkValues(){
		if(txtQuestionNum.getText().trim().equals("") || txtQuetion.getText().trim().equals("") ||
				txtAnswer1.getText().trim().equals("") || txtAnswer2.getText().trim().equals("") ||
				txtAnswer3.getText().trim().equals("") ||txtAnswer4.getText().trim().equals("")){
			ui.ShowMessageBox("ERROR", "Please fill all fields", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		int input;
		try {  
			input=Integer.parseInt( txtQuestionNum.getText() );  
		}  
		catch( Exception ex) {  
			ui.ShowMessageBox("ERROR", "Quetion number must be numeric", JOptionPane.ERROR_MESSAGE);
			return false;  
		}
		if(input<1 || input>999) {
			ui.ShowMessageBox("ERROR", "Question number must be in range 1-999", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}

	/**
	 * Question ID setter
	 * @param id Question ID
	 */
	public void setQuestionID(int id){
		qID=id;
		cmbSubjectNum.setEnabled(false);
		txtQuestionNum.setEnabled(false);
		CommandMessage ms = new CommandMessage(CommandMessage.GET_QUESTION,new Object[]{id});
		try {
			c.sendToServer(ms);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
